const path = require("path");
const fse = require("fs-extra");
const Page = require("../../models/pages");
const config = {
  noTpl: ["admin"],
  template: {
    1: "admin",
    2: "simple_app",
  },
};

// 生成路由
const joinRoutersToProject = async (id, project, url, name) => {
  try {
    const projectCode = project.code;
    const templateName = config.template[project.template];

    // 验证和清理输入参数
    if (config.noTpl.includes(templateName)) {
      return;
    }

    const _Page = await Page.findOne({ _id: id });
    if (!_Page) {
      throw new Error("Page not found");
    }

    const routerFilePath = path.join(
      __dirname,
      `../../projects/${projectCode}/src/router/constant.js`
    );

    // 安全删除目标文件
    await fse.remove(routerFilePath);

    let fileContent = "";
    try {
      fileContent = await fse.readFile(routerFilePath, "utf8");
    } catch (err) {
      if (err.code !== "ENOENT") {
        throw err;
      }
    }

    // 清理字符串并解析为 JSON
    fileContent = fileContent
      .replace(/import\s*\{.*\}\s*from\s*".*";?\s*/g, "")
      .replace("export const constantRouterMap =", "")
      .replace(/\s+/g, "")
      .replaceAll(",}", "}")
      .replaceAll(",]", "]")
      .replace(/;\s*$/g, "")
      .replace(/"_import\(\"([^\"]+)\"\)"/g, '""')
      .replace(/([a-zA-Z_]+):/g, '"$1":')
      .replace(/\,\n\]/g, "]");

    let constantRoutes = [];
    try {
      constantRoutes = JSON.parse(fileContent);
    } catch (err) {
      console.warn("Failed to parse existing router file content:", err);
    }

    // 更新路由配置
    const routePaths = new Set(constantRoutes.map((route) => route.path));

    if (_Page.url !== url && routePaths.has(_Page.url)) {
      constantRoutes = constantRoutes.filter(
        (route) => route.path !== _Page.url
      );
      routePaths.delete(_Page.url);
    }

    if (!routePaths.has(url)) {
      constantRoutes.push({
        path: url,
        name: name,
        component: `_import("${url}")`,
      });
      routePaths.add(url);
    } else {
      const idx = constantRoutes.findIndex((route) => route.path === url);
      constantRoutes[idx] = {
        path: url,
        name: name,
        component: `_import("${url}")`,
      };
    }

    if (!routePaths.has("/")) {
      constantRoutes.push({
        path: "/",
        redirect: constantRoutes[0]?.path || "/",
      });
      routePaths.add("/");
    }

    // 生成最终的路由配置字符串
    constantRoutes = JSON.stringify(constantRoutes).replace(
      /"_import\\("([^"]+)"\\)"/g,
      '_import("$1")'
    );

    const finalContent = `import { _import } from "./_import";
export const constantRouterMap = ${constantRoutes};`;

    await fse.outputFile(routerFilePath, finalContent, "utf8");
  } catch (error) {
    console.error("Error in joinRoutersToProject:", error);
    throw error;
  }
};

module.exports = joinRoutersToProject;
